package org.xnsg.app.controller;

import com.alibaba.fastjson.JSON;
import com.eova.aop.AopContext;
import com.eova.aop.MetaObjectIntercept;
import com.eova.common.Easy;
import com.eova.common.utils.xx;
import com.eova.model.*;
import com.eova.service.sm;
import com.eova.template.common.util.TemplateUtil;
import com.eova.vo.MenuConfig;
import com.eova.widget.WidgetManager;
import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtomImp;
import com.jfinal.plugin.activerecord.Record;
import org.xnsg.app.controller.utils.ControllerHelper;
import org.xnsg.app.core.bean.Result;

import java.sql.SQLException;
import java.util.*;

/**
 * @author zhaopan
 * @date :2017/4/21
 * @Description:
 */
public class ProductionController extends Controller {

    final Controller ctrl = this;
    protected MetaObjectIntercept intercept = null;
    private String errorInfo = "";
    private final Record record = new Record();
    public void list() {
        User user = (User) this.getSessionAttr("user");
        String menuCode = this.getPara(0);
        Menu menu = Menu.dao.findByCode(menuCode);
        MenuConfig config = menu.getConfig();
        String objectCode = config.getObjectCode();
        //MetaObject object = MetaObject.dao.getByCode(objectCode);
        List fields = MetaField.dao.queryByObjectCode(objectCode);
        List<Button> btnList = Button.dao.queryByMenuCode(menuCode, user.getInt("rid").intValue());
        Map resultMap = new HashMap();
        //resultMap.put("isQuery", Boolean.valueOf(MetaObject.dao.isExistQuery(objectCode)));
        //resultMap.put("menu", menu);
        //按钮
        List<String> btnNames=new ArrayList<String>();
        for(Button btn:btnList){
            btnNames.add(btn.getStr("name"));
        }
        resultMap.put("btnList", btnNames);

        //resultMap.put("object", object);
        resultMap.put("fields", fields);
        //生产单位分类
        resultMap.put("mainenttype", ControllerHelper.comboJson(null, "c_aj_jydw", "mainenttype", new Object[]{this.getSessionAttr("user")}));
        //生产单位类型
        //resultMap.put("enttype", ControllerHelper.comboJson(null, "c_aj_jydw", "enttype", new Object[]{this.getSessionAttr("user")}));
        this.renderJson(new Result(resultMap));
    }

    public void detail() {
        String objectCode = this.getPara(0);
        String pkValue = this.getPara(1);
        String userId = getPara("userId");
        User user = User.dao.getByLoginId(getPara("userId"));
        this.setSessionAttr("user", user);
        MetaObject object = sm.meta.getMeta(objectCode);
        Record record = Db.use(object.getDs()).findById(object.getView(), object.getPk(), new Object[]{pkValue});

        MetaField ei;
        Object value;
        for (Iterator var7 = object.getFields().iterator(); var7.hasNext(); ei.put("value", value)) {
            ei = (MetaField) var7.next();
            String key = ei.getEn();
            value = record.get(key);
            if (value == null) {
                value = "";
            }
        }

       // WidgetManager.buildRef(this, object);
        Map resultMap = new HashMap();
       // resultMap.put("object", object);

        ///生产单位分类
        List<Record> mainenttypes=ControllerHelper.comboJson(null, "c_aj_jydw", "mainenttype", new Object[]{user});
        Map<String, String> mainenttypeMap = new HashMap<String, String>();
        for (Record re : mainenttypes)
        {
            mainenttypeMap.put(String.valueOf(re.get("id")), re.getStr("cn"));
        }
        //状态
        List<Record> statuses= ControllerHelper.comboJson(null, "c_aj_jydw", "status", new Object[]{user});
        Map<String, String> statusMap = new HashMap<String, String>();
        for (Record re : statuses)
        {
            statusMap.put(String.valueOf(re.get("id")), re.getStr("cn"));
        }
        //生产单位类型
        List<Record>enttypes=ControllerHelper.comboJson(null, "c_aj_jydw", "enttype", new Object[]{user});
        Map<String, String> enttypeMap = new HashMap<String, String>();
        for (Record re : enttypes)
        {
            enttypeMap.put(String.valueOf(re.get("id")), re.getStr("cn"));
        }

        //网格人员
        String insertowner=ControllerHelper.findCnByEn("c_aj_jydw", "insertowner", String.valueOf(record.get("insertowner")), new Object[]{user});


        for (MetaField field : object.getFields()){
            if ("mainenttype".equals(field.getStr("en")))
            {
                resultMap.put(field.getStr("en"), mainenttypeMap.get(String.valueOf(field.get("value"))));
            }else if("status".equals(field.getStr("en"))){
                resultMap.put(field.getStr("en"), statusMap.get(String.valueOf(field.get("value"))));
            }else if("enttype".equals(field.getStr("en"))){
                resultMap.put(field.getStr("en"), enttypeMap.get(String.valueOf(field.get("value"))));
            }else{
                resultMap.put(field.getStr("en"), String.valueOf(field.get("value")));
            }
        }
        resultMap.put("insertowner", insertowner==null?"":insertowner);
        // this.buildWidget(resultMap);
        this.removeSessionAttr("user");
        this.renderJson(new Result(resultMap));
    }
    public void add() throws Exception {
        String objectCode = this.getPara(0);
        MetaObject object = sm.meta.getMeta(objectCode);
        Iterator var4 = object.getFields().iterator();

//        while(var4.hasNext()) {
//            MetaField ac = (MetaField)var4.next();
//            ac.put("is_disable", Boolean.valueOf(false));
//        }

        //WidgetManager.buildRef(this, object);
        this.intercept = (MetaObjectIntercept) TemplateUtil.initIntercept(object.getBizIntercept());
        if(this.intercept != null) {
            AopContext ac1 = new AopContext(this.ctrl, object);
            this.intercept.addInit(ac1);
        }

        Map resultMap = new HashMap();
       // resultMap.put("object", object);
        //resultMap.put("fields", object.getFields());
        resultMap.put("mainenttype", ControllerHelper.comboJson(null, "c_aj_jydw", "mainenttype", new Object[]{this.getSessionAttr("user")}));
        resultMap.put("enttype", ControllerHelper.comboJson(null, "c_aj_jydw", "enttype", new Object[]{this.getSessionAttr("user")}));
        resultMap.put("status", ControllerHelper.comboJson(null, "c_aj_jydw", "status", new Object[]{this.getSessionAttr("user")}));
        this.renderJson(new Result(resultMap));

    }
    public void update() throws Exception {
        String pkValue = this.getPara(1);
        User user = User.dao.getByLoginId(getPara("userId"));
        this.setSessionAttr("user", user);
        MetaObject object = this.buildFormData(true);
        this.intercept = (MetaObjectIntercept)TemplateUtil.initIntercept(object.getBizIntercept());
        if(this.intercept != null) {
            AopContext ac = new AopContext(this.ctrl, object);
            this.intercept.updateInit(ac);
        }
        Map resultMap = new HashMap();
        Record record = Db.use(object.getDs()).findById(object.getView(), object.getPk(), new Object[]{pkValue});

        // resultMap.put("object", object);
       // resultMap.put("fields", object.getFields());
        resultMap.put("mainenttype_List", ControllerHelper.comboJson(null, "c_aj_jydw", "mainenttype", new Object[]{this.getSessionAttr("user")}));
       // resultMap.put("enttype_List", ControllerHelper.comboJson(null, "c_aj_jydw", "enttype", new Object[]{this.getSessionAttr("user")}));
        resultMap.put("status_List", ControllerHelper.comboJson(null, "c_aj_jydw", "status", new Object[]{this.getSessionAttr("user")}));
        String insertowner=ControllerHelper.findCnByEn("c_aj_jydw", "insertowner", String.valueOf(record.get("insertowner")), new Object[]{this.getSessionAttr("user")});
        //{"text_field":"nickname","data":"[{\"id\":2113041,\"nickname\":\"陈家坊村第十网格用户\"}]"}
        try
        {
            Map<String,String> jsonMap = JSON.parseObject(insertowner, Map.class);
            List<Map> dataList =JSON.parseArray(jsonMap.get("data"), Map.class);
            insertowner= (String) dataList.get(0).get("nickname");
        }catch (Exception e){
            e.printStackTrace();
        }
        Map qxMap=new HashMap();
        for (MetaField field : object.getFields()){
            resultMap.put(field.getStr("en"), String.valueOf(field.get("value")));
            resultMap.put(field.getStr("en")+"_qx", (boolean)field.get("is_update"));
        }
        //;

        resultMap.put("enttype_List",ControllerHelper.comboJson("select tid ID, tname CN from dt_dwtype where tlevel=3 and ptid ="+resultMap.get("mainenttype"),null, null, new Object[]{this.getSessionAttr("user")}));

        resultMap.put("insertowner", insertowner);


        this.removeSessionAttr("user");
        this.renderJson(new Result(resultMap));

    }

    public void doUpdate() {
        String objectCode = this.getPara(0);
        final MetaObject object = sm.meta.getMeta(objectCode);
        final Map reMap = WidgetManager.buildData(this, object.getFields(), this.record, object.getPk(), false);
        Object pkValue = this.record.get(object.getPk());
        this.intercept = (MetaObjectIntercept)TemplateUtil.initIntercept(object.getBizIntercept());
        boolean flag = Db.tx(new IAtomImp(object, reMap) {
            public boolean run() throws SQLException {
                try {
                    AopContext e = new AopContext(ProductionController.this.ctrl, ProductionController.this.record);
                    String msg;
                    if(ProductionController.this.intercept != null) {
                        msg = ProductionController.this.intercept.updateBefore(e);
                        if(!xx.isEmpty(msg)) {
                            ProductionController.this.errorInfo = msg;
                            return false;
                        }
                    }

                    if(!xx.isEmpty(this.object.getTable())) {
                        System.out.println(JsonKit.toJson(ProductionController.this.record));
                        Db.use(this.object.getDs()).update(this.object.getTable(), this.object.getPk(), ProductionController.this.record);
                    } else {
                        WidgetManager.operateView(this.object.getPk(), this.reMap, "update");
                    }

                    if(ProductionController.this.intercept != null) {
                        msg = ProductionController.this.intercept.updateAfter(e);
                        if(!xx.isEmpty(msg)) {
                            ProductionController.this.errorInfo = msg;
                        }
                    }

                    return true;
                } catch (Exception var3) {
                    ProductionController.this.errorInfo = TemplateUtil.buildException(var3);
                    return false;
                }
            }
        });
        if(!flag) {
            this.renderJson(new Easy(this.errorInfo));
        } else if(!flag) {
            this.renderJson(new Easy("修改失败" + this.errorInfo));
        } else {
            EovaLog.dao.info(this, 2, object.getStr("code") + "[" + pkValue + "]");
            if(this.intercept != null) {
                try {
                    ArrayList e = new ArrayList();
                    e.add(this.record);
                    AopContext ac = new AopContext(this, e);
                    String msg = this.intercept.updateSucceed(ac);
                    if(!xx.isEmpty(msg)) {
                        this.errorInfo = msg;
                    }
                } catch (Exception var9) {
                    this.errorInfo = TemplateUtil.buildException(var9);
                    this.renderJson(new Easy("修改成功,updateSucceed拦截执行异常!" + this.errorInfo));
                    return;
                }
            }

            this.renderJson(new Easy());
        }
    }
    public MetaObject buildFormData(boolean isEdit) {
        String objectCode = this.getPara(0);
        String pkValue = this.getPara(1);
        MetaObject object = sm.meta.getMeta(objectCode);
        Record record = Db.use(object.getDs()).findById(object.getView(), object.getPk(), new Object[]{pkValue});

        MetaField ei;
        Object value;
        for(Iterator var7 = object.getFields().iterator(); var7.hasNext(); ei.put("value", value)) {
            ei = (MetaField)var7.next();
            String key = ei.getEn();
            value = record.get(key);
            if(value == null) {
                value = "";
            }

//            if(!isEdit) {
//                ei.set("is_disable", Boolean.valueOf(true));
//            }
        }

      //  WidgetManager.buildRef(this, object);

        //this.buildWidget();
        return object;
    }
}
